package com.ms.p2p.controller.app;

import com.alibaba.dubbo.common.json.JSONObject;
import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.ResponseUtils;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.FuyouBank;
import com.ms.p2p.entity.RetMap;
import com.ms.p2p.entity.UserThreadLocal;
import com.ms.p2p.entity.account.*;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.enums.LoanStatus;
import com.ms.p2p.plugin.payment.PaymentPluginBundle;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.utils.HttpTookit;
import com.ms.p2p.utils.TradeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chensk on 2018/3/15.
 */

@Controller
@RequestMapping({ "/api" })
public class ApiMemberController extends BaseController{

    @Autowired
    PaymentPluginBundle paymentPluginBundle;

    @Reference
    private MemberAccountProvider account_Service;



    @Reference
    private LoanProvider loanProvider;
    @Reference
    private MemberAccountBankProvider bankService;
    @Reference
    private MemberWithDrawProvider memberWithDrawProvider;
    @Reference
    private MemberAccountRechargeProvider rechargeService;
    @Reference
    private MemberAccountRecordProvider logService;
    @Reference
    private SettingProvider settingProvider;
    @Reference
    private MemberAccountProvider memberAccountProvider;
    @Reference
    private PayMethodProvider payMethodProvider;
    @Reference
    private MemberAccountBankProvider memberAccountBankProvider;

    @Reference
    private CertiFiCationProvider certificationProvider;


    @Reference
    private IdCardQueryProvider idCardQueryProvider;

    @Reference
    private LoanTenderRecordProvider loanTenderRecordProvider;

    @Reference
    private FuyouProvider fuyouProvider;
    @Reference
    private RedPacketProvider redPacketProvider;
    @Reference
    DictionaryProvider dictionaryProvider;


    @Reference
    private MemberProvider memberProvider;

    @Reference
    private UnBindProvider bankCardLogProvider;


    @Reference
    private BankCardImgProvider bankCardImgProvider;

    @RequestMapping(value = {"/member/bank/tounbind"},produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public HashMap toUnbindBankCard(HttpServletRequest request, HttpSession session) throws Exception{

        Member member = UserThreadLocal.get();
        HashMap map = new HashMap();
        AccountBank accountBank = bankService.findByUserId(member.getId());
        // 根据用户ID和银行卡查询有没有申请记录，并查出正在申请状态
        BankCardImgLog bankCardImgLog = bankCardLogProvider.findByUserIdAndBankId(member.getId(),accountBank.getId(),0);

        if(bankCardImgLog==null){
            return RetMap.Error("不存在");
        }

        return RetMap.Success("解绑中");
    }
    @RequestMapping(value = {"/member/bank/unbind"},produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public HashMap unbind(HttpServletRequest request, HttpSession session) throws Exception{
        Member member = UserThreadLocal.get();
        AccountBank accountBank = bankService.findByUserId(member.getId());
        BankCardImgLog log = new BankCardImgLog();
        log.setAddip(HttpTookit.getRealIpAddr(request));
        log.setAddtime(MsDateUtils.getTime());
        log.setBank_cardno(accountBank.getBank_cardno());
        log.setRemark("解绑");
        log.setStatus(0);
        log.setBank_id(accountBank.getId());
        log.setUser_id(member.getId());
        String[] imgall = request.getParameterValues("imgall");
        Integer user_id = member.getId();
        List<BankCardImg> list = new ArrayList<BankCardImg>();
        if (imgall != null) {
            BankCardImg img = new BankCardImg();
            int size = java.lang.reflect.Array.getLength(imgall);

            for (int i = 0; i < size; i++) {
                img.setUser_id(user_id);
                img.setImg(imgall[i]);

                list.add(img);
            }

        }

        bankCardLogProvider.insert(log,list);
        return RetMap.Success("提交成功");
    }

    /**
     * 修改登录密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "oldpass", message = "旧 密码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "就密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认不能为空")
    })
    @RequestMapping("/member/passchange")
    @ResponseBody
    public HashMap passchange(String oldpass, String pass1, String pass2) {

        Member member = UserThreadLocal.get();
        // 密码正则
        if (StringUtils.isBlank(oldpass) || !StringUtils.equals(DigestUtils.md5Hex(oldpass),
                member.getLogin_password())) {
            return RetMap.Error("旧密码输入不正确");
        }
        if (StringUtils.isBlank(pass1)) {
            return RetMap.Error("新密码不能为空！");
        }
        if (!StringUtils.equals(pass1, pass2)) {
            return RetMap.Error("两次输入的密码不一致！");
        }
        if (pass1.length()<6){
            return RetMap.Error("密码必须6-20位,必须包含字母、数字、其他字符组合");
        }
        member.setLogin_password(DigestUtils.md5Hex(pass1));
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);
        return RetMap.Success("密码重置成功，请重新登陆！");
    }

    /**
     * 修改支付密码
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "oldpass", message = "旧 密码不能为空"),
            @RequiredStringValidator(fieldName = "pass1", message = "就密码不能为空"),
            @RequiredStringValidator(fieldName = "pass2", message = "确认不能为空")

    })
    @RequestMapping("/member/paypasswordchange")
    @ResponseBody
    public HashMap paypasswordchange(String oldpass, String pass1, String pass2) {
        Member member = UserThreadLocal.get();
        member = memberProvider.findById(member.getId());
        // 密码正则
        String pwdRegex = "^(.*){6,20}$";

        if (StringUtils.isBlank(pass1)) {
            return RetMap.Error("新密码不能为空！");
        }

        if (StringUtils.isBlank(oldpass) || !StringUtils.equals(DigestUtils.md5Hex(oldpass),
                member.getPayment_password())) {
            return  RetMap.Error("原交易密码输入不正确");
        }


        if (!StringUtils.equals(pass1, pass2)) {
            return  RetMap.Error("两次输入的密码不一致！");
        }

        if (!pass1.matches(pwdRegex)) {
            return  RetMap.Error("密码必须6-20位");
        }

        if (member.getLogin_password().equals(
                DigestUtils.md5Hex(pass1))) {
            return  RetMap.Error("交易密码不能和登陆密码相同！");
        }

        member.setPayment_password(DigestUtils.md5Hex(pass1));
        member.setUp_time(String.valueOf(System.currentTimeMillis()));
        member.setUp_ip(AppContext.getRemoteIp());
        memberProvider.updateById(member);
        return  RetMap.Success("密码重置成功，请重新登陆！");
    }





    @RequestMapping({ "/member/redpacket/list" })
    @ResponseBody
    public HashMap list(HttpServletRequest request, Integer currentPage, String status) {
        Member user =  UserThreadLocal.get();
        PageBean page = new PageBean();
        page.setCurrentPage(currentPage);
        HashMap retMap = RetMap.Success("数据获取成功");
        retMap.put("list",redPacketProvider.findPager(page,status,user.getId(),null));
        return retMap;
    }

    /**
     * 提交提现申请
     */
    @Validations(requiredStrings = {
            @RequiredStringValidator(fieldName = "money", message = "提现金额不能为空"),
            @RequiredStringValidator(fieldName = "paypassword", message = "交易密码不能为空")

    }
    )
    @RequestMapping("/member/docash")
    @ResponseBody
    public HashMap submit(Double money,String paypassword) throws Exception {

        Member user =  UserThreadLocal.get();
        Account account = memberAccountProvider.findByUserId(user.getId());
        AccountBank banCard = bankService.findByUserId(user.getId());
        if (banCard == null) {
            return RetMap.Error("请先绑定您的银行卡!") ;
        }
        if(!memberProvider.findById(user.getId()).getPayment_password().equals(DigestUtils.md5Hex(paypassword))){
            return RetMap.Error("交易密码错误!");
        }
        if (banCard.getStatus() == 0) {
            return RetMap.Error("为了防止恶意提现,请先使用该银行卡充值，才能提现!");
        }
        if (money < 100 || money > 50000) {
            return RetMap.Error("单笔提现金额为100-50000元");
        }

        if (BigDecimal.valueOf(money).compareTo(account.getBalance()) > 0) {
            return RetMap.Error("提现金额大于账户最大可用余额，请重新操作!");
        }


        Withdraw widthdraw = new Withdraw();
        widthdraw.setUser_id(user.getId());
        widthdraw.setTrade_no(TradeUtil.getTrano()+"");
        widthdraw.setTotal(new BigDecimal(money));
        widthdraw.setAddtime(MsDateUtils.getTime());
        widthdraw.setAddip(AppContext.getRemoteIp());
        widthdraw.setCrad_no(banCard.getBank_cardno());
        widthdraw.setBank(banCard.getBank());
        widthdraw.setBranch(banCard.getBranch());
        memberWithDrawProvider.withDrawApply(widthdraw, AppContext.getRemoteIp());

        return RetMap.Success("提现成功");
    }

    /**
     * 保存银行卡
     */
    @RequestMapping(value = {"/member/bank/save"},produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public HashMap bankSave(HttpServletRequest request, HttpSession session) throws Exception{
        Member user  =   UserThreadLocal.get();

        AccountBank mybank = bankService.findByUserId(user.getId());
        if(mybank!=null){
            throw  new NoticeException("您已绑定银行卡");
        }
        AccountBank  bankCardNo = new AccountBank();
        List<FuyouBank> list = fuyouProvider.getList();
        for(FuyouBank bank:list){
            if(bank.getBank_code().equals(request.getParameter("bank_code"))){
                bankCardNo.setBank(bank.getBank_name());
                bankCardNo.setBank_img_mobile(bank.getBank_img_mobile());
            }
        }
        bankCardNo.setBank_code(request.getParameter("bank_code"));
        if(bankCardNo.getBank()==null)
            throw new NoticeException("不支持该银行");
            bankCardNo.setProvince(request.getParameter("s_province"));
            bankCardNo.setCity(request.getParameter("s_city"));
            bankCardNo.setArea(request.getParameter("s_county"));
            bankCardNo.setBranch(request.getParameter("branch"));
            bankCardNo.setBank_cardno(request.getParameter("bank_cardno"));
            bankCardNo.setUser_id(user.getId());
            bankCardNo.setAddtime(MsDateUtils.getTime());
            bankCardNo.setAddip(AppContext.getRemoteIp());
            bankCardNo.setStatus(1);
            bankService.insert(bankCardNo);
        return RetMap.Success("保存成功");
    }

    /**
     * 申请实名认证
     */
    @RequestMapping("/member/certification")
    @ResponseBody
    public HashMap certification(HttpServletRequest request, HttpSession session

            , @RequestParam("real_name") String real_name
            , @RequestParam("idnumber") String idnumber

    )  {

        Member user = UserThreadLocal.get();
        if(certificationProvider.findByUserId(user.getId())!=null){
            throw new NoticeException("您已经实名认证");
        }
            int other = certificationProvider.findOther(idnumber, user.getId());
        if(other>0){
            throw new NoticeException("一个平台不能实名2个相同身份证");
        }
            Auth realName =   new Auth();

            realName.setUser_id(user.getId());
            realName.setReal_name(real_name);
            realName.setId_number(idnumber);

            realName.setAddtime(MsDateUtils.getTime());
            realName.setAddip(AppContext.getRemoteIp());
            realName.setStatus(0);
            String birthday;

            int sex = 0;

            if(idnumber.length()==15){
                birthday=idnumber.substring(6,12);


            }else if(idnumber.length()==18){
                birthday=idnumber.substring(6,14);
            }else{
                throw  new NoticeException("身份证有误");
            }

            if (idnumber.length() == 15 || idnumber.length() == 18)
            {
                String lastValue = idnumber.substring(idnumber.length() - 1, idnumber.length());

                if (lastValue.trim().toLowerCase().equals("x")||lastValue.trim().toLowerCase().equals("e"))
                {
                    sex = 0;
                }
                else
                {
                    sex = Integer.parseInt(lastValue) % 2;

                }
            }
            realName.setSex(sex);
            realName.setBirthdate(birthday);//生日奖励发放


try{
        if(idCardQueryProvider.idCardQuery(idnumber,real_name)){



            realName.setStatus(1);

            certificationProvider.insert(realName);
        }else{
            realName.setStatus(0);



        }
    } catch (NoticeException e) {
        realName.setStatus(0);
    }
    catch (Exception e) {
        logger.error(e);
        return RetMap.Error("出现未知错误");
    }
        if(certificationProvider.findByUserId(user.getId())!=null){
            realName.setId(certificationProvider.findByUserId(user.getId()).getId());
            certificationProvider.update(realName);
        }else{
            certificationProvider.insert(realName);
        }

        if(realName.getStatus()==1)
            return RetMap.Success("认证成功");
        return RetMap.Error("身份证错误");

    }


    /**
     * 收支明细
     * logType 资金类型 可以为null
     * beginDate开始时间 可以为null
     * endDate 结束时间 可以weinull
     *
     */
    @RequestMapping({ "/member/account/log" })
    @ResponseBody
    public HashMap cashdata(String logType, String beginDate, String endDate, String currentPage, Model model){
        PageBean page = new PageBean();
        if (StringUtils.isNotBlank(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        Member user = UserThreadLocal.get();
        List<Map<String, Object>> logs =
                logService.findPager(user.getId() + "", null, logType, beginDate, endDate, page.getBegin(),
                        page.getPageSize());

        for (Map<String,Object> map:logs){
            map.put("type_cn",dictionaryProvider.getDictValue("account_type",map.get("type")+""));
        }

        page.setTotalCount(logService.findCount(user.getId() + "", null,logType, beginDate, endDate));
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("list", logs);
        retMap.put("page", page);
        return retMap;
    }



    /*
      *用户资金查询
      *
      * */
    @RequestMapping({ "/member/account" })
    @ResponseBody
    public HashMap account(){
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("item",  memberAccountProvider.findByUserId(UserThreadLocal.get().getId()));


        return retMap;
    }


    /*
      *用户资金查询
      *
      * */
    @RequestMapping({ "/member/isReal" })
    @ResponseBody
    public String isReal(HttpServletResponse response) throws IOException {

        Auth auth = certificationProvider.findByUserId(UserThreadLocal.get().getId());
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("item",auth);
        response.getWriter().print(net.sf.json.JSONObject.fromObject(retMap));
        return null;
    }
    /*
      *用户资金查询
      *
      * */
    @RequestMapping({ "/member/isBankBind" })
    @ResponseBody
    public String isBankBind(HttpServletResponse response) throws IOException {
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("item",  memberAccountBankProvider.findByUserId(UserThreadLocal.get().getId()));
       response.getWriter().print(net.sf.json.JSONObject.fromObject(retMap));
        return null;

    }
    /*
      *用户资金查询
      *
      * */
    @RequestMapping({ "/member/isPhoneBind" })
    @ResponseBody
    public HashMap isPhoneBind(){
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("phone_status",  memberProvider.findById(UserThreadLocal.get().getId()).getStatus());
        return retMap;
    }



    /*
   *我的投资-还款中
   * */
    @RequestMapping("/member/loan/biddingAndcollection")
    @ResponseBody
    public HashMap collection(HttpServletRequest request, PageBean page) throws Exception {
        Member user = UserThreadLocal.get();
        page.getBegin();
        List<Map<String, Object>> borrows = loanTenderRecordProvider.findLoanPager(user.getId(), LoanStatus.STATUS_9.getValue()+"",page);
        page.setTotalCount(loanTenderRecordProvider
                .findLoanCount(user.getId(),LoanStatus.STATUS_9.getValue()+""));
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("list", borrows);
        retMap.put("page", page);
        return retMap;
    }
    /**
     * 我的投资-已还款
     */
    @RequestMapping({ "/member/loan/payed" })
    @ResponseBody
    public HashMap payed(HttpServletRequest request,
                              HttpServletResponse response, HttpSession session) throws Exception {
        Member user = UserThreadLocal.get();

        PageBean page = new PageBean();
        String currentPage = request.getParameter("currentPage");
        if (currentPage != null && !("".equals(currentPage))) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        List<Map<String, Object>> loans = loanTenderRecordProvider.findLoanPager(user.getId(), LoanStatus.STATUS_6.getValue()+"",page);
        page.setTotalCount(loanTenderRecordProvider
                .findLoanCount(user.getId(),LoanStatus.STATUS_6.getValue()+""));
        HashMap retMap = com.ms.p2p.entity.RetMap.Success("获取数据成功");
        retMap.put("list", loans);
        retMap.put("page", page);
        return retMap;
    }




}
